package com.xxkj.drugtraceability.net
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.xxkj.drugtraceability.App.Companion.CONTEXT
import com.xxkj.drugtraceability.R
import okhttp3.ResponseBody
import org.json.JSONException
import org.json.JSONObject
import retrofit2.Converter
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.reflect.Type

/**
 * author: zhoujingjin
 * created on: 2022/2/28 8:47
 * description:给base_bean data赋值
 */
class GsonResponseDataConverter<T>(val gson: Gson, val adapter: TypeAdapter<out Any>, val clazz: Type) : Converter<ResponseBody, T> {
    override fun convert(value: ResponseBody): T? {
        return try {
            var response = value.string()
            val a = booleanArrayOf(false)
            if (a[0]) {
                var line:String? = ""
                var text:String = ""
                val inputStream: InputStream = CONTEXT.resources.openRawResource(R.raw.sstt)
                val isReader = InputStreamReader(inputStream)
                val bfReader = BufferedReader(isReader)
                while (bfReader.readLine().also { line = it } != null) {
                    text += """
            $line
            
            """.trimIndent()
                }
                response = text
            }

            val jsonObject = JSONObject(response)
            var code = ""
            var msg = ""
            var jsonContent = ""
            if (response.startsWith("{\"data\"")){
                var data = jsonObject.getJSONObject("data")
                if (data.has("code"))
                code =   data.getString("code")
                else{
                    if (jsonObject.has("code"))
                        code =   jsonObject.getString("code")
                }
                if (data.has("msg"))
                msg =   data.getString("msg")
                else {
                    if (jsonObject.has("msg"))
                        msg =   jsonObject.getString("msg")
                }
                jsonContent = "{\"code\":\"$code\",\"msg\":\"$msg\",\"data\":${data.toString()}}"
            } else{
                val code =   jsonObject.getString("code")
                val msg =   jsonObject.getString("msg")
                jsonContent = "{\"code\":\"$code\",\"msg\":\"$msg\",\"data\":${jsonObject.toString()}}"
            }
                val out = gson.fromJson(jsonContent, clazz) as WanResponse<T>
            if (code!="200"){
                out.errorData = msg
            }
                out as T
        } catch (e: JSONException) {
            e.printStackTrace()
            null
        }catch (e: Exception) {
            e.printStackTrace()
            null
        } finally {
            value.close()
        }
    }
}